package com.ellfors.common.ext

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch

fun <T> Flow<T>.observeOnState(
    owner: LifecycleOwner,
    state: Lifecycle.State = Lifecycle.State.STARTED,
    block: (T) -> Unit
) {
    owner.lifecycleScope.launch {
        owner.repeatOnLifecycle(state) {
            this@observeOnState.collect {
                block(it)
            }
        }
    }
}

fun <T> Flow<T>.observe(
    owner: LifecycleOwner, block: (T) -> Unit
) {
    owner.lifecycleScope.launch {
        this@observe.collect {
            block(it)
        }
    }
}

fun <T> MutableSharedFlow<T>.emitOnScope(
    scope: CoroutineScope, data: T
) {
    scope.launch {
        this@emitOnScope.emit(data)
    }
}